package com.xpffly.design.composite.demo;

import com.xpffly.design.composite.demo.service.IBranch;
import com.xpffly.design.composite.demo.service.ILeaf;
import com.xpffly.design.composite.demo.service.IRoot;
import com.xpffly.design.composite.demo.service.impl.Branch;
import com.xpffly.design.composite.demo.service.impl.Leaf;
import com.xpffly.design.composite.demo.service.impl.Root;

import java.util.ArrayList;

/**
 * @Author: 午夜学徒
 * @Date: 2021/8/5 23:09
 * @Description：组合模式 demo 场景类
 */
public class Scene {
    public static void main(String[] args) {
        // 创建一个根节点
        IRoot ceo = new Root("张三", "总经理", 100000);
        // 创建三个 部门经理
        IBranch devLeader = new Branch("李四", "开发部门经理", 50000);
        IBranch saleLeader = new Branch("王五", "销售部门经理", 60000);
        IBranch testLeader = new Branch("赵六", "测试部门经理", 40000);
        // 小组长
        IBranch devTeamLeader = new Branch("王一", "研发一组组长", 30000);
        IBranch devTeamLeader2 = new Branch("王二", "研发二组组长", 30000);
        // 员工
        ILeaf dev1 = new Leaf("研发1", "开发人员", 10000);
        ILeaf dev2 = new Leaf("研发2", "开发人员", 12000);
        ILeaf dev3 = new Leaf("研发3", "开发人员", 14000);
        ILeaf dev4 = new Leaf("研发4", "开发人员", 9000);
        ILeaf dev5 = new Leaf("研发5", "开发人员", 8000);
        ILeaf dev6 = new Leaf("研发6", "开发人员", 10000);
        ILeaf sale1 = new Leaf("销售1", "销售人员", 13000);
        ILeaf test1 = new Leaf("测试1", "测试人员", 10000);
        ILeaf assist = new Leaf("小苏", "ceo秘书", 10000);
        // 组装树
        ceo.add(devLeader);
        ceo.add(saleLeader);
        ceo.add(testLeader);
        ceo.add(assist);
        // 定义研发部门下的部门结构
        devLeader.add(devTeamLeader);
        devLeader.add(devTeamLeader2);
        // 添加研发人员
        devTeamLeader.add(dev1);
        devTeamLeader.add(dev2);
        devTeamLeader.add(dev3);
        devTeamLeader.add(dev4);
        devTeamLeader2.add(dev5);
        devTeamLeader2.add(dev6);
        // 销售部门
        saleLeader.add(sale1);
        // 测试部门
        testLeader.add(test1);
        // 打印树状结构
        System.out.println(ceo.getInfo());
        System.out.println("-------------------我是分隔符-------------------");
        // 打印出整个树状结构
        getAllSubOrdinateInfo(ceo.getSubordinateInfo());
    }

    /**
     * 遍历所有的树枝节点，打印出信息
     *
     * @param subOrdinateList
     */
    private static void getAllSubOrdinateInfo(ArrayList subOrdinateList) {
        int length = subOrdinateList.size();
        // 不要在 for循环中计算list的长度，会比较耗时
        for (int i = 0; i < length; i++) {
            Object o = subOrdinateList.get(i);
            if (o instanceof Leaf) {
                ILeaf employee = (ILeaf) o;
                System.out.println(employee.getInfo());
            } else {
                IBranch branch = (IBranch) o;
                System.out.println(branch.getInfo());
                // 再递归调用
                getAllSubOrdinateInfo(branch.getSubordinateInfo());
            }

        }
    }
}
